<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>编辑文章</title>
    <link rel="stylesheet" href="" th:href="@{/lib/editormd/css/editormd.css}">
    <link rel="stylesheet" href="" th:href="@{/lib/layui/css/layui.css}">
    <style>
        html, body {
            height: 100%;
        }

        /*暂时处理编辑器高度*/
        #test-editor {
            min-height: 680px;
        }
    </style>
</head>

<body>

<!--添加编辑容器-->
<form action="" class="layui-form" lay-filter="form">
    <div class="layui-form-item">

            <label class="layui-form-label">一级分类*</label>
            <div class="layui-input-inline">
                <select name="category1" lay-filter="category1">
                    <option th:each="obj : ${categories}" th:text="${obj.name}" th:value="${obj.id}"></option>
                </select>
            </div>

            <label class="layui-form-label">二级分类*</label>
            <div class="layui-input-inline">
                <select name="category2" lay-filter="category2">
                    <option value="0">-请选择-</option>
                </select>
            </div>


            <label class="layui-form-label">三级分类*</label>
            <div class="layui-input-inline">
                <select name="category3" lay-filter="category3">
                    <option value="0">-请选择-</option>
                </select>
            </div>

        <div class="layui-input-inline" style="width: 70%;margin-left:2%">
            <input type="text" lay-filter="title" name="title" style="background-color:rgb(255, 250, 227)"
                   class="layui-input" placeholder="请输入标题，100个字以内">
        </div>
        <div class="layui-input-inline">
            <input type="button" class="layui-btn" value="发布" id="publish">
        </div>
    </div>
    <div id="test-editor" class="layui-form-item" style="height: 100%">
        <div class="layui-input-block ">
            <textarea style="display:none;" class="layui-textarea" name="content"></textarea>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">标签</label>
        <div class="layui-input-inline">
            <input type="text" name="title" lay-verify="tags"
                   autocomplete="off" placeholder="请输入标签，比如hello" class="layui-input" id="tagBtn">
        </div>
    </div>
    <div class="layui-form-item" id="tagSpans">

    </div>
</form>
<!--引入layui-->
<script th:src="@{/lib/layui/layui.js}"></script>
<script src="https://cdn.bootcss.com/jquery/3.4.0/jquery.min.js"></script>
<script type="text/javascript" th:src="@{/lib/editormd/editormd.min.js}"></script>
<script>
    var editor;
    $(function () {
        editor = editormd("test-editor",{
            height:"100%",
            path:"/lib/editormd/lib/"
            ,watch:false  //实时预览功能
        });
    });

    //layui
    layui.use(['jquery','form','layer'],function () {

        var $ = layui.jquery;
        var form = layui.form;
        var layer = layui.layer;

        //监听一级分类
        form.on('select(category1)',function (data) {
            var c1 = data.value;

            $('select[name=category2]').empty();
            $('select[name=category3]').empty();

            $.ajax({
                url:'/article/sub?parent='+c1,
                type:'POST',
                success:function (data) {
                    var html = '<option value="0">-请选择-</option>';
                    for (var i = 0; i < data.length; i++){
                        html += '<option value="' + data[i].id + '">' +data[i].name +'</option>'
                    }
                    $('select[name=category2]').empty().html(html);
                    form.render();
                }
            })

        })
        //监听二级分类
        form.on('select(category2)',function (data) {
            var c2 = data.value;


            $('select[name=category3]').empty();

            $.ajax({
                url:'/article/sub?parent='+c2,
                type:'POST',
                success:function (data) {
                    var html = '<option value="0">-请选择-</option>';
                    for (var i = 0; i < data.length; i++){
                        html += '<option value="' + data[i].id + '">' +data[i].name +'</option>'
                    }
                    $('select[name=category3]').empty().html(html);
                    form.render();
                }
            })

        })

        //点击发布
        $('#publish').click(function () {
            //获取表单数据，发送请求到后端
            //构建我们的tags 数据
            var tags= [];
            $('#tagSpans input').each(function () {
                var obj = {
                    "name":$(this).attr('data')
                };
                tags.push(obj);
            });

            //需要传输的数据
            var obj = {
                "title":$('input[name=title]').val(),
                "content":editor.getMarkdown(),
                "category":{
                    "id":$("select[name=categoryId]").val()
                },
                "tags":tags
            };
            $.ajax({
                url:'/article',
                type:'post',
                contentType:'application/json',
                data:JSON.stringify(obj),
                success:function (data) {
                    if(data.code = 2000){
                        if(data.date != null){
                            //此时文章是有ID的，这里要额外处理 todo
                        }
                        layer.msg(data.msg,{
                            icon:6,//成功图标
                            time:1000
                        });
                    }else{
                        layer.msg(data.msg);
                    }
                }
            })
        })

        //监听 粘贴事件 ctrl + v
        $('#test-editor').get(0).addEventListener('paste',function () {
            //获取图片资源，通过ajax 发送过去
            var items = event.clipboardData && event.clipboardData.items;
            var file = null;
            if(items && items.length){
                //检索剪切板 items
                for (var i = 0; i < items.length;i++){
                    if(items[i].type.indexOf('image') !== -1){
                        file = items[i].getAsFile();
                        break;
                    }
                }
            }
            if(file == null){
                return;
            }
            var formData = new FormData();
            formData.append('file',file);
            $.ajax({
                url:'/up/image',
                type:'POST',
                data:formData,
                contentType:false,
                processData:false,
                beforeSend: function () {
                    layer.msg('<i class = "layui-icon layui-icon-upload"> </i>正在上传，客观别急..',{
                        time:1500
                    })
                },
                success:function (data) {
                    //获取 markdownUrl,写入当前文本当中
                    //var markdownUrl = data.markdownUrl;
                    //editor.insertValue(markdownUrl);
                    var obj = JSON.parse(data);
                    //通过obj.data.url 可以得到url地址 address 为拼接的 图片地址写法
                    var url = obj.data.url;
                    if(url.toString().indexOf(".jpg") > 0 || url.toString().indexOf(".png") > 0){
                        var address = '![](' + url + ')' ;
                        editor.insertValue(address);
                    }else{
                        alert("bu不合法的图片格式");
                    }
                },
                error: function (xhr, error) {
                    alert('error');
                }
            });
        })

        //监听 键盘点击事件 keydown
        //参数 ev 为键盘的下标
        $('#tagBtn').get(0).addEventListener('keydown',function (ev) {

            //keyCode 为对应按键的键码
            // 13 表示 enter 键
            if(ev.keyCode == 13){
                //获取这个里面的值
                var v = $(this).val();
                //处理v值，是否已经存在
                var hasTag = false;
                $("#tagSpans span").each(function () {
                    var temp = $(this).html();
                    var v1 = v+'<i class="layui-icon-delete layui-icon" style="font-size: 30px; color: red;"></i>';
                    if(v1 == temp){
                        hasTag = true;
                        return;
                    }
                })
                if(hasTag){
                    $(this).val('');
                    return;
                }
                if (v === '') {
                    // 空内容不予处理
                    layer.msg('不能有空标签哦！',{
                        time:1500
                    })
                    return;
                }
                var html = '<span class="layui-btn" data="' + v + '">' + v + '<i class="layui-icon-delete layui-icon" style="font-size: 30px; color: red;"></i></span>';
                $(this).val('');
                //往 $('#tagSpans') 标签内 的最后面 添加 html
                $('#tagSpans').append(html);


                form.render();
            }

        })

        // 监听delete icon
        $(document).on('click','#tagSpans i',function () {
            //删除自身
            $(this).parent().remove();
        })
    })
</script>
</body>
</html>